package com.yf.listview3;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private MyOpenHelper openHelper;
	private List<User> users = new ArrayList<User>();
	private ListView lv_list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		openHelper = new MyOpenHelper(this);
		lv_list = (ListView) findViewById(R.id.lv_list);
	}
	
	public void insert(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		String sql = "insert into user(name,phone) values('yf','13699999999')";
		db.execSQL(sql);
		sql = "insert into user(name,phone) values('ywj','13688888888')";
		db.execSQL(sql);
		db.close();
		Toast.makeText(this, "插入数据成功", Toast.LENGTH_SHORT).show();
	}
	
	public void query(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		String sql = "select * from user";
		Cursor cursor = db.rawQuery(sql, null);
		
		while(cursor.moveToNext()) {
			User user = new User(cursor.getString(1), cursor.getString(2));
			users.add(user);
		}
		cursor.close();
		db.close();
		
		lv_list.setAdapter(new MyAdapter());
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return users.size();
		}

		@Override
		public Object getItem(int position) {
			return users.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			
			if (convertView == null) {
				view = View.inflate(MainActivity.this, R.layout.item, null);
			} else {
				view = convertView;
			}
			
			TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
			TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
			User user = users.get(position);
			tv_name.setText(user.name);
			tv_phone.setText(user.phone);
			
			return view;
		}

	}

	private class MyOpenHelper extends SQLiteOpenHelper {

		public MyOpenHelper(Context context) {
			super(context, "listview3", null, 1);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE user(_id integer primary key autoincrement,name varchar(20),phone varchar(12));");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
		}

	}
}
